package com.tbl.modules.wms.service.Impl.webserviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.tbl.common.config.ConRunningMap;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.constant.EbsInterfaceEnum;
import com.tbl.modules.wms.constant.JaxbUtil;
import com.tbl.modules.wms.constant.XmlToolsUtil;
import com.tbl.modules.wms.dao.baseinfo.ShelfDAO;
import com.tbl.modules.wms.dao.instorage.InstorageDAO;
import com.tbl.modules.wms.dao.instorage.InstorageDetailDAO;
import com.tbl.modules.wms.dao.interfacelog.InterfaceDoDAO;
import com.tbl.modules.wms.dao.interfacelog.InterfaceLogDAO;
import com.tbl.modules.wms.dao.outstorage.AllOutStorageDAO;
import com.tbl.modules.wms.dao.outstorage.OutStorageDetailDAO;
import com.tbl.modules.wms.dao.outstorage.OutstorageDAO;
import com.tbl.modules.wms.dao.storageinfo.StorageInfoDAO;
import com.tbl.modules.wms.dao.webservice.FewmDAO;
import com.tbl.modules.wms.entity.baseinfo.Shelf;
import com.tbl.modules.wms.entity.instorage.Instorage;
import com.tbl.modules.wms.entity.instorage.InstorageDetail;
import com.tbl.modules.wms.entity.interfacelog.InterfaceDo;
import com.tbl.modules.wms.entity.outstorage.AllOutStorage;
import com.tbl.modules.wms.entity.outstorage.OutStorage;
import com.tbl.modules.wms.entity.outstorage.OutStorageDetail;
import com.tbl.modules.wms.entity.requestxml.*;
import com.tbl.modules.wms.entity.storageinfo.StorageInfo;
import com.tbl.modules.wms.service.webserviceutil.JavaBeanToXml;
import com.tbl.modules.wms.service.webservice.server.FewmService;
import com.tbl.modules.wms2.dao.operation.QualityInfoDAO;
import com.tbl.modules.wms2.dao.ordermanage.delivery.DeliveryDao;
import com.tbl.modules.wms2.entity.operation.EmergencyMaterialDTO;
import com.tbl.modules.wms2.entity.operation.QualityInfoEntity;
import com.tbl.modules.wms2.entity.ordermanage.delivery.DeliveryEntity;
import com.tbl.modules.wms2.entity.requestXML.FEWMS202_data;
import com.tbl.modules.wms2.entity.requestXML.FEWMS203_data;
import com.tbl.modules.wms2.entity.requestXML.FEWMS204_data;
import com.tbl.modules.wms2.entity.requestXML.FEWMS204_oa_qcline;
import com.tbl.modules.wms2.service.operation.QualityInfoService;
import com.tbl.modules.wms2.service.ordermanage.delivery.DeliveryService;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.xml.bind.JAXBException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * Webservice接口服务端实现
 * @author 70486
 */
@Service
public class FewmServiceImpl extends ServiceImpl<FewmDAO, T> implements FewmService {

	/**
	 * 后台打印日志
	 */
	private final Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * Webservice服务的接口方法DAO
	 */
    @Resource
    private FewmDAO fewmDAO;
	/**
	 * 库存
	 */
	@Autowired
    private StorageInfoDAO storageInfoDAO;
	/**
	 * 入库管理-订单
	 */
	@Autowired
    private InstorageDAO instorageDAO;
	/**
	 * 入库管理-订单详情
	 */
	@Autowired
    private InstorageDetailDAO instorageDetailDAO;
	/**
	 * 出库信息
	 */
	@Autowired
    private OutstorageDAO outstorageDAO;
	/**
	 * 出库信息详情
	 */
	@Resource
    private OutStorageDetailDAO outStorageDetailDAO;
	/**
	 * 出库
	 */
	@Resource
    private AllOutStorageDAO allOutStorageDAO;
	/**
	 * 接口日志记录
	 */
	@Autowired
    private InterfaceLogDAO interfaceLogDAO;
	/**
	 * 库位
	 */
	@Autowired
	private ShelfDAO shelfDAO;
	/**
	 * 离线接口执行
	 */
	@Autowired
	private InterfaceDoDAO interfaceDoDAO;

	@Resource
	private DeliveryDao deliveryDao;
	@Autowired
	private DeliveryService deliveryService;
	@Autowired
	private QualityInfoService qualityInfoService;
	@Resource
	private QualityInfoDAO qualityInfoDAO;

    /**
     * FEWMS003  WMS接口-销售退货数据同步
     * @param  para
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS003(String para) {
		logger.info("#####	ebs---->>>>>wms	销售退货数据同步FEWMS003：" + para);
    	Map<String,Object> resultMap = new HashMap<>(2);
        FEWMS003_data data03 = null ;
        try {
            data03 = JaxbUtil.xmlToBean(para, FEWMS003_data.class);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        
        //手动new出来抛出的异常或手动return返回，不会回滚数据库事务，所以需要在解析数据保存前，先对数据进行空值判断
        if(data03!=null && data03.getItem()!=null) {
	        for (FEWMS003_items fewms003Items : data03.getItem()) {
	        	if (StringUtils.isEmpty(fewms003Items.getOeheader()) || StringUtils.isEmpty(fewms003Items.getOeline()) ||
						StringUtils.isEmpty(fewms003Items.getItemnum()) || StringUtils.isEmpty(fewms003Items.getCustomerid()) ||
						StringUtils.isEmpty(fewms003Items.getQty()) || StringUtils.isEmpty(fewms003Items.getUom()) || StringUtils.isEmpty(fewms003Items.getOrgid())) {
	        		logger.info("旧质保号为:"+fewms003Items.getOldqano()+"的数据存在非法空值！参数如下："+"\n"+ "oeheader:"+fewms003Items.getOeheader()+"\n"+
							"oeline:"+fewms003Items.getOeheader()+"\n"+ "itemnum:"+fewms003Items.getOeheader()+"\n"+ "customerid:"+fewms003Items.getOeheader()+"\n"+
							"qty:"+fewms003Items.getOeheader()+"\n"+ "uom:"+fewms003Items.getOeheader()+"\n"+ "orgid:"+fewms003Items.getOeheader());
	            	resultMap = new HashMap<String, Object>(2) {{
	                    put("code", 1);
	                    put("msg", "旧批次号为:" + fewms003Items.getOldqano()+"的数据存在非法空值！");
	                }};
					interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS003, "WMS接口-销售退货数据同步", para, JSONObject.toJSONString(resultMap),
							fewms003Items.getOldqano(), fewms003Items.getNewqano());
					logger.info("#####	wms---->>>>>ebs	销售退货数据同步FEWMS003：" + JSONObject.toJSONString(resultMap));
	                return resultMap;
	            }else {
	            	//如果传过来的盘具为空，那么给予默认盘具
	            	if(StringUtils.isBlank(fewms003Items.getDrummodel())) {
						fewms003Items.setDrummodel("1327100013");
					}
	            }
	        }
        }else {
        	resultMap = new HashMap<String, Object>(2) {{
                put("code", 1);
                put("msg", "失败，销售退货同步数据为空!");
            }};
			interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS003, "WMS接口-销售退货数据同步", para, JSONObject.toJSONString(resultMap),"","");
			logger.info("#####	wms---->>>>>ebs	销售退货数据同步FEWMS003：" + JSONObject.toJSONString(resultMap));
            return resultMap;
        }

        List<Instorage> lstInstorage;
        InstorageDetail instorageDetail,oldInstorageDetail = null;
        Instorage instorage;
        Long instorageId;

		for (FEWMS003_items FEWMS003_item : data03.getItem()) {
			try {
				while (ConRunningMap.containsItem(EbsInterfaceEnum.FEWMS003 + FEWMS003_item.getNewqano())){
					TimeUnit.MILLISECONDS.sleep(5000);
				}
				//把接口编码+质保号放到内存中
				ConRunningMap.addItem(EbsInterfaceEnum.FEWMS003 + FEWMS003_item.getNewqano());
				lstInstorage = instorageDAO.selectList(new EntityWrapper<Instorage>()
						.eq("ORDERNO", FEWMS003_item.getRmaorderno())
						.eq("ORG", FEWMS003_item.getOrgid())
						.eq("ORDERLINE", FEWMS003_item.getRmalineno()));
				if(lstInstorage.size()==0) {
					instorage = new Instorage();
					//工单号
					instorage.setEntityNo("SYSXSTH"+ DateUtils.getDays());
					//订单编号
					instorage.setOrderNo(FEWMS003_item.getRmalineno());
					//数据创建时间
					instorage.setCreateTime(new Date());
					//订单行号
					instorage.setOrderline(FEWMS003_item.getRmalineno());
					instorage.setOrg(FEWMS003_item.getOrgid());
					instorageDAO.insert(instorage);
					instorageId = instorage.getId();
				}else {
					instorageId = lstInstorage.get(0).getId();
				}

				//根据传过来的原质保号查询原来的货物信息，如果存在，那么把原质保号+_T
				List<InstorageDetail> lstInstorageDetail =instorageDetailDAO.selectByMap(new HashMap<String,Object>(1){{
					put("QACODE",FEWMS003_item.getOldqano());
				}});
				if (lstInstorageDetail!=null && lstInstorageDetail.size()>0){
					oldInstorageDetail = lstInstorageDetail.get(0);
				}

				//新的批次号（rfid）
				String rfid_batchno = new DecimalFormat("000000000000").format(fewmDAO.selectSeqRfid());

				instorageDetail = new InstorageDetail();
				instorageDetail.setPId(instorageId);
				instorageDetail.setOrdernum(FEWMS003_item.getRmaorderno());
				instorageDetail.setOrderline(FEWMS003_item.getRmalineno());
				instorageDetail.setMaterialCode(FEWMS003_item.getItemnum());
				instorageDetail.setBatchNo(rfid_batchno);
				instorageDetail.setQaCode(FEWMS003_item.getNewqano());
				instorageDetail.setSalesCode(FEWMS003_item.getSalescode());
				instorageDetail.setSalesName(FEWMS003_item.getSalesname());
				instorageDetail.setRfid(rfid_batchno);
				instorageDetail.setCreatetime(new Date());
				instorageDetail.setState(1);
				//销售退货
				instorageDetail.setStoragetype(1L);
				instorageDetail.setMeter(FEWMS003_item.getQty());
				instorageDetail.setUnit(FEWMS003_item.getUom());
				instorageDetail.setOrg(FEWMS003_item.getOrgid());
				instorageDetail.setOeheader(FEWMS003_item.getOeheader());
				instorageDetail.setOeline(FEWMS003_item.getOeline());
				instorageDetail.setLocationid(FEWMS003_item.getLocationid());
				instorageDetail.setCustomerid(FEWMS003_item.getCustomerid());
				instorageDetail.setDishnumber(FEWMS003_item.getDrummodel());
				instorageDetail.setReturnqacode(oldInstorageDetail != null ? oldInstorageDetail.getQaCode() : "");
				instorageDetailDAO.insert(instorageDetail);

				if(oldInstorageDetail!=null){
					oldInstorageDetail.setQaCode(oldInstorageDetail.getQaCode()+"_T");
					instorageDetailDAO.updateById(oldInstorageDetail);
				}

				resultMap = new HashMap<String, Object>(2) {{
					put("code", 0);
					put("msg", "成功");
				}};
			}catch (Exception e){
				e.printStackTrace();
				resultMap.put("code", 1);
				resultMap.put("msg", e.getStackTrace());
			}

			ConRunningMap.removeItem(EbsInterfaceEnum.FEWMS003 + FEWMS003_item.getNewqano());
		}
		interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS003, "WMS接口-销售退货数据同步", para, JSONObject.toJSONString(resultMap),"", "");
		logger.info("#####	wms---->>>>>ebs	销售退货数据同步FEWMS003：" + JSONObject.toJSONString(resultMap));
        return resultMap;
    }

    /**
     * FEWMS004  WMS接口-采购退货
     * @param  para
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS004(String para) {
		logger.info("#####	ebs---->>>>>wms	采购退货数据同步FEWMS004：" + para);
		Map<String, Object> resultMap;
		FEWMS004_data data04 = null;
		try {
			data04 = JaxbUtil.xmlToBean(para, FEWMS004_data.class);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		//要批量删除的库存主键
		List<Long> lstStorageInfoId = new ArrayList<>();
		//要批量修改状态（状态改为“已退库”）的标签初始化表质保号集合
		List<String> lstInstorageDetailQacodes = new LinkedList<>();
		//要批量修改的库存
		List<StorageInfo> storageInfos = new LinkedList<>();
		//登记退库记录表
		List<AllOutStorage> lstAllOutStorage = new LinkedList<>();

		if (data04!=null) {
			data04.batchs.reservdata.forEach(fewms004Reservdata -> {
				try {
					while (ConRunningMap.containsItem(EbsInterfaceEnum.FEWMS004 + fewms004Reservdata.batchno)) {
						TimeUnit.MILLISECONDS.sleep(5000);
					}
					//把接口编码+批次号放到内存中
					ConRunningMap.addItem(EbsInterfaceEnum.FEWMS004 + fewms004Reservdata.batchno);
					List<StorageInfo> lstStorageInfo = storageInfoDAO.selectList(new EntityWrapper<StorageInfo>().eq("BATCH_NO", fewms004Reservdata.batchno));
					if (lstStorageInfo.size() > 0) {
						StorageInfo storageInfo = lstStorageInfo.get(0);
						double differenceValue = Double.parseDouble(storageInfo.getMeter()) - Double.parseDouble(fewms004Reservdata.getMeter());
						if (differenceValue == 0) {
							lstInstorageDetailQacodes.add(storageInfo.getQaCode());
							lstStorageInfoId.add(storageInfo.getId());
						} else {
							storageInfo.setMeter(String.valueOf(differenceValue));
							storageInfos.add(storageInfo);
						}

						//登记采购退货清单
						AllOutStorage allOutStorage = new AllOutStorage();
						allOutStorage.setMaterialCode(storageInfo.getMaterialCode());
						allOutStorage.setBatchNo(storageInfo.getBatchNo());
						allOutStorage.setQaCode(storageInfo.getQaCode());
						allOutStorage.setShelfCode(storageInfo.getShelfCode());
						allOutStorage.setWarehouseCode(storageInfo.getWarehouseCode());
						allOutStorage.setMeter(fewms004Reservdata.getMeter());
						allOutStorage.setRfid(storageInfo.getRfid());
						allOutStorage.setInstoragetime(new Date());
						allOutStorage.setOrg(storageInfo.getOrg());
						allOutStorage.setSalesCode(storageInfo.getSalesCode());
						allOutStorage.setSalesName(storageInfo.getSalesName());
						allOutStorage.setInstorageid(null);
						allOutStorage.setState(storageInfo.getState());
						allOutStorage.setEntityno(storageInfo.getEntityNo());
						allOutStorage.setOrderno(storageInfo.getOrderno());
						allOutStorage.setOrderline(storageInfo.getOrderline());
						allOutStorage.setDishnumber(storageInfo.getDishnumber());
						//采购退货 类型为2
						allOutStorage.setType(2);
						lstAllOutStorage.add(allOutStorage);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				ConRunningMap.removeItem(EbsInterfaceEnum.FEWMS004 + fewms004Reservdata.batchno);
			});
		}

		//批量插入采购退货清单
		if (lstAllOutStorage.size()>0){
			allOutStorageDAO.insertScrapBatches(lstAllOutStorage);
		}
		//批量删除库存
		if(lstStorageInfoId.size()>0){
			storageInfoDAO.deleteBatchIds(lstStorageInfoId);
		}
		//批量修改标签初始化表状态为“已退库”
		if(lstInstorageDetailQacodes.size()>0){
			InstorageDetail instorageDetailEntity = new InstorageDetail();
			instorageDetailEntity.setPurchaseReturnTime(new Date());
			instorageDetailEntity.setState(5);
			instorageDetailDAO.update(instorageDetailEntity, new EntityWrapper<InstorageDetail>().in("QACODE", lstInstorageDetailQacodes));
		}
		//批量修改库存米数
		if (storageInfos.size()>0){
			storageInfoDAO.updateScrapBatchesStorageInfo(storageInfos);
		}

		resultMap = new HashMap<String, Object>(2) {{
			put("code", 0);
			put("msg", "成功");
		}};

		interfaceLogDAO.insertLog("FEWMS004", "WMS接口-采购退货", para, JSONObject.toJSONString(resultMap),"","");
		logger.info("#####	wms---->>>>>ebs	采购退货数据同步FEWMS004：" + JSONObject.toJSONString(resultMap));
		return resultMap;
	}

    /**
     * FEWMS005  WMS接口-保留接口
     * @param para
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS005(String para) {
		logger.info("#####	ebs---->>>>>wms	保留FEWMS005：" + para);
        Map<String,Object> resultMap = Maps.newHashMap();
        try {
			FEWMS005_data data05 = JaxbUtil.xmlToBean(para, FEWMS005_data.class);
			if(data05.reservdata!=null) {
				for (FEWMS005_reservdata reservdata : data05.reservdata) {
					if ("INSERT".equals(reservdata.getStatus())) {
						//更新入库明细表（标签初始化信息）
						fewmDAO.updateOrderInstorageDetail(reservdata.getLotnumber(), reservdata.getOrderline(), reservdata.getOrdernum());
						//更新重新绑定RFID表
						fewmDAO.updateOrderRfidBindDetail(reservdata.getLotnumber(), reservdata.getOrderline(), reservdata.getOrdernum());
					} else if ("DELETE".equals(reservdata.getStatus())) {
						//更新入库明细表（标签初始化信息）
						fewmDAO.updateOrderInstorageDetail(reservdata.getLotnumber(), "", "");
						//更新重新绑定RFID表
						fewmDAO.updateOrderRfidBindDetail(reservdata.getLotnumber(), "", "");
					}
				}
			}

			resultMap = new HashMap<String, Object>(2) {{
				put("code", 0);
				put("msg", "成功");
			}};
        } catch (Exception e) {
            e.printStackTrace();
			resultMap.put("code", 1);
			resultMap.put("msg", e.getStackTrace());
        }

		interfaceLogDAO.insertLog("FEWMS005", "WMS接口-保留接口", para, JSONObject.toJSONString(resultMap),"","");
		logger.info("#####	ebs---->>>>>wms	保留FEWMS005：" + JSONObject.toJSONString(resultMap));
        return resultMap;
    }

    /**
     * FEWMS006  WMS接口-发货单（提货单）接口
     * @param para 请求报文
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS006(String para) {
		logger.info("#####	ebs---->>>>>wms	发货单数据同步FEWMS006：" + para);
		Map<String,Object> resultMap;
		FEWMS006_data data06 = null;
		para = para.replaceAll("&", "&amp;");
		try{
			data06 = JaxbUtil.xmlToBean(para, FEWMS006_data.class);
		}catch (JAXBException e){
			e.printStackTrace();
		}

		List<OutStorageDetail> lstBatchOutStorageDetail = new ArrayList<>();
		//新增
		if(data06!=null && data06.slipdata!=null) {
			for (FEWMS006_slipdata slipdata : data06.slipdata) {
				if(slipdata.batchs!=null && slipdata.batchs.batchsline!=null) {
					for (FEWMS006_batchsline batchsline : slipdata.batchs.batchsline) {
						try{
							while (ConRunningMap.containsItem(EbsInterfaceEnum.FEWMS006 + batchsline.zhibao)){
								TimeUnit.MILLISECONDS.sleep(5000);
							}
							//把接口编码+质保号放到内存中
							ConRunningMap.addItem(EbsInterfaceEnum.FEWMS006 + batchsline.zhibao);

							OutStorage outStorage;
							InstorageDetail instorageDetail;
							List<InstorageDetail> instorageDetailList = instorageDetailDAO.selectByMap(new HashMap<String,Object>(1) {{
								put("QACODE",batchsline.getZhibao());
							}});

							if(instorageDetailList==null||instorageDetailList.size()!=1) {
								instorageDetail = null;
							} else {
								instorageDetail = instorageDetailList.get(0);
							}

							//在出库单表中没有这个出库单号
							if(outstorageDAO.selectCount(new EntityWrapper<OutStorage>().eq("SHIP_NO", slipdata.shipno)) == 0) {
								outStorage = new OutStorage();
								outStorage.setShipNo(slipdata.shipno);
								outStorage.setPrintTime(slipdata.printtime);
								outStorage.setContractNo(slipdata.contractno);
								outStorage.setOrderNo(slipdata.orderno);
								outStorage.setOrderLine(slipdata.orderline);
								outStorage.setTransportName(slipdata.transportname);
								outStorage.setCustomer(slipdata.customer);
								outStorage.setOrg(slipdata.org);
								//未提交
								outStorage.setState(1);
								outStorage.setCreateTime(new Date());
								if(instorageDetail!=null) {
									outStorage.setSalesCode(instorageDetail.getSalesCode());
									outStorage.setSalesName(instorageDetail.getSalesName());
								}
								outstorageDAO.insert(outStorage);
							}else {
								outStorage = outstorageDAO.selectByMap(new HashMap<String,Object>(1){{
									put("SHIP_NO", slipdata.shipno);
								}}).get(0);
							}

							OutStorageDetail outStorageDetail = new OutStorageDetail();
							outStorageDetail.setBatchNo(batchsline.batchno);
							outStorageDetail.setMeter(batchsline.mishu);
							outStorageDetail.setPId(outStorage.getId());
							outStorageDetail.setState(Constant.INT_ONE);
							outStorageDetail.setDetailid(StringUtils.isNotEmpty(batchsline.detialid)?Long.parseLong(batchsline.detialid):null);
							//组织机构
							outStorageDetail.setOrg(slipdata.org);
							outStorageDetail.setContractno(slipdata.contractno);
							outStorageDetail.setOrderno(slipdata.orderno);
							outStorageDetail.setOrderline(slipdata.orderline);
							outStorageDetail.setTransportname(slipdata.transportname);
							outStorageDetail.setCustomer(slipdata.customer);
							outStorageDetail.setQaCode(batchsline.zhibao);
							outStorageDetail.setUnit(batchsline.uom);
							outStorageDetail.setMeter(batchsline.mishu);
							if(instorageDetail!=null) {
								outStorageDetail.setMaterialCode(instorageDetail.getMaterialCode());
								outStorageDetail.setShelfCode(instorageDetail.getShelfCode());
								outStorageDetail.setRfid(instorageDetail.getRfid());
								outStorageDetail.setWarehouseCode(instorageDetail.getWarehouseCode());
								outStorageDetail.setDishnumber(instorageDetail.getDishnumber());
							}

							if (outStorageDetailDAO.selectCount(new EntityWrapper<OutStorageDetail>()
									.eq("QACODE",outStorageDetail.getQaCode())
									.eq("P_ID",outStorageDetail.getPId()))==0){
								lstBatchOutStorageDetail.add(outStorageDetail);
							}
						}catch (Exception e){
							e.printStackTrace();
						}

						ConRunningMap.removeItem(EbsInterfaceEnum.FEWMS006 + batchsline.zhibao);
					}
				}
			}
		}
		//批量插入
		if (lstBatchOutStorageDetail.size()>0){
			outStorageDetailDAO.insertOutStorageDetailBatch(lstBatchOutStorageDetail);
		}

		//删除
		if(data06!=null&&data06.batchsdet!=null) {
			data06.batchsdet.forEach(batchsdet-> outStorageDetailDAO.deleteByMap(new HashMap<String,Object>(1) {{
				put("DETAILID",batchsdet.detialid);
			}}));
		}

		resultMap = new HashMap<String, Object>(2) {{
			put("code", 0);
			put("msg", "成功");
		}};

		logger.info("#####	wms---->>>>>ebs	发货单数据同步FEWMS006：" + JSONObject.toJSONString(resultMap));
		interfaceLogDAO.insertLog("FEWMS006", "WMS接口-发货单接口", para, JSONObject.toJSONString(resultMap),"","");
		return resultMap;
	}

    /**
     * FEWMS010  WMS接口-报废接口
     * @param para
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS010(String para) {
		logger.info("#####	ebs---->>>>>wms	报废FEWMS010：" + para);
        Map<String,Object> resultMap;
		FEWMS010_data data10 = null;
        try {
			data10 = JaxbUtil.xmlToBean(para, FEWMS010_data.class);
		}catch (JAXBException e){
        	e.printStackTrace();
		}

		if (data10!=null && data10.baofei!=null) {
			List<StorageInfo> storageInfoAllDeleteList;
			List<AllOutStorage> allOutStorageAllDeleteList;
			StorageInfo storageInfo;
			AllOutStorage allOutStorage = null;
			//报废与撤销报废的处理逻辑，需要依次顺序执行，不能批量处理，因为同一次接口中可能出现对同一批次反复做报废撤销
			for (FEWMS010_batchs fewms010Batchs : data10.baofei) {
				try{
					while (ConRunningMap.containsItem(EbsInterfaceEnum.FEWMS010 + fewms010Batchs.getLotnum())){
						TimeUnit.MILLISECONDS.sleep(5000);
					}
					//把接口编码+质保号放到内存中
					ConRunningMap.addItem(EbsInterfaceEnum.FEWMS010 + fewms010Batchs.getLotnum());

					//根据批次号查询库存
					storageInfoAllDeleteList = storageInfoDAO.selectList(new EntityWrapper<StorageInfo>().eq("BATCH_NO", fewms010Batchs.lotnum));

					if (fewms010Batchs.qty.startsWith(".")) {
						fewms010Batchs.qty = "0" + fewms010Batchs.qty;
					}
					if (fewms010Batchs.qty.startsWith("-.")) {
						fewms010Batchs.qty = "-0" + fewms010Batchs.qty.substring(1);
					}

					//报废
					if (!fewms010Batchs.qty.startsWith("-")) {
						if (storageInfoAllDeleteList != null && storageInfoAllDeleteList.size() > 0) {
							storageInfo = storageInfoAllDeleteList.get(0);

							//加入备份表
							allOutStorage = new AllOutStorage();
							allOutStorage.setMaterialCode(storageInfo.getMaterialCode());
							allOutStorage.setBatchNo(fewms010Batchs.lotnum);
							allOutStorage.setQaCode(storageInfo.getQaCode());
							allOutStorage.setShelfCode(storageInfo.getShelfCode());
							allOutStorage.setWarehouseCode(storageInfo.getWarehouseCode());
							allOutStorage.setRfid(storageInfo.getRfid());
							allOutStorage.setMeter(fewms010Batchs.qty);
							allOutStorage.setInstoragetime(storageInfo.getInStorageTime());
							allOutStorage.setOrg(storageInfo.getOrg());
							allOutStorage.setSalesCode(storageInfo.getSalesCode());
							allOutStorage.setSalesName(storageInfo.getSalesName());
							allOutStorage.setInstorageid(storageInfo.getInStorageId());
							allOutStorage.setState(storageInfo.getState());
							allOutStorage.setEntityno(storageInfo.getEntityNo());
							allOutStorage.setOrderno(storageInfo.getOrderno());
							allOutStorage.setOrderline(storageInfo.getOrderline());
							allOutStorage.setDishnumber(storageInfo.getDishnumber());
							//报废 类型为3
							allOutStorage.setType(Constant.INT_THREE);
							allOutStorageDAO.insert(allOutStorage);

							//报废米数与库存米数相等，直接出库
							if (Double.parseDouble(fewms010Batchs.qty) == Double.parseDouble(storageInfo.getMeter())) {
								//库位释放
								if (StringUtils.isNotBlank(storageInfo.getShelfCode())) {
									Shelf shelfEntity = new Shelf();
									shelfEntity.setState(1);
									shelfDAO.update(shelfEntity, new EntityWrapper<Shelf>().eq("CODE", storageInfo.getShelfCode()));
								}

								//库存删除
								storageInfoDAO.deleteById(storageInfo.getId());
							} else {
								//报废米数小于库存米数，做扣减
								storageInfo.setMeter(String.valueOf(Double.parseDouble(storageInfo.getMeter()) - Double.parseDouble(fewms010Batchs.qty)));
								storageInfoDAO.updateById(storageInfo);
							}
						}
					} else {
						//取消报废
						allOutStorageAllDeleteList = allOutStorageDAO.selectList(new EntityWrapper<AllOutStorage>()
								.eq("BATCH_NO", fewms010Batchs.lotnum)
								.eq("METER", String.valueOf(Double.parseDouble(fewms010Batchs.qty) * -1)));
						if (allOutStorageAllDeleteList != null && allOutStorageAllDeleteList.size() > 0) {
							allOutStorage = allOutStorageAllDeleteList.get(0);
						}
						//库存存在，则补加
						if (storageInfoAllDeleteList != null && storageInfoAllDeleteList.size() > 0) {
							storageInfo = storageInfoAllDeleteList.get(0);
							storageInfo.setMeter(String.valueOf(Double.parseDouble(storageInfo.getMeter()) - Double.parseDouble(fewms010Batchs.qty)));
							storageInfoDAO.updateById(storageInfo);
						} else {
							//库存不存在，全量加
							if (allOutStorage != null) {
								storageInfo = new StorageInfo();
								storageInfo.setMaterialCode(allOutStorage.getMaterialCode());
								storageInfo.setBatchNo(allOutStorage.getBatchNo());
								storageInfo.setQaCode(allOutStorage.getQaCode());
								storageInfo.setShelfCode(allOutStorage.getShelfCode());
								storageInfo.setWarehouseCode(allOutStorage.getWarehouseCode());
								storageInfo.setMeter(allOutStorage.getMeter());
								storageInfo.setRfid(allOutStorage.getRfid());
								storageInfo.setInStorageTime(allOutStorage.getInstoragetime());
								storageInfo.setOrg(allOutStorage.getOrg());
								storageInfo.setSalesCode(allOutStorage.getSalesCode());
								storageInfo.setSalesName(allOutStorage.getSalesName());
								storageInfo.setInStorageId(allOutStorage.getInstorageid());
								storageInfo.setState(allOutStorage.getState());
								storageInfo.setEntityNo(allOutStorage.getEntityno());
								storageInfo.setOrderno(allOutStorage.getOrderno());
								storageInfo.setOrderline(allOutStorage.getOrderline());
								storageInfo.setDishnumber(allOutStorage.getDishnumber());
								storageInfoDAO.insert(storageInfo);

								//库位占用
								if (StringUtils.isNotBlank(allOutStorage.getShelfCode())) {
									Shelf shelfEntity = new Shelf();
									shelfEntity.setState(0);
									shelfDAO.update(shelfEntity, new EntityWrapper<Shelf>().eq("CODE", allOutStorage.getShelfCode()));
								}
								//删除备份表数据
								allOutStorageDAO.deleteById(allOutStorage.getId());
							}
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}

				ConRunningMap.removeItem(EbsInterfaceEnum.FEWMS010 + fewms010Batchs.getLotnum());
			}
		}

		resultMap = new HashMap<String, Object>(2) {{
			put("code", 0);
			put("msg", "成功");
		}};

		interfaceLogDAO.insertLog("FEWMS010", "WMS接口-报废接口", para, JSONObject.toJSONString(resultMap),"","");
		logger.info("#####	wms---->>>>>ebs	报废FEWMS010：" + JSONObject.toJSONString(resultMap));
        return resultMap;
    }

    /**
     * FEWMS017 标签初始化（mes接口，正常生产）
     * @param para 请求报文
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS017(String para) {
    	logger.info("#####	mes---->>>>>wms	标签初始化FEWMS017：" + para);
        FEWMS017_data data17 = null;
        Map<String,Object> resultMap = Maps.newHashMap();
        try{
			data17 = JaxbUtil.xmlToBean(para.replaceAll("&","&amp;").replaceAll("'","&apos;")
					.replaceAll("\"","&quot;"), FEWMS017_data.class);
		}catch (JAXBException e){
        	e.printStackTrace();
		}

		if (StringUtils.isEmpty(data17.getEntityno()) || StringUtils.isEmpty(data17.getOrderno()) || StringUtils.isEmpty(data17.getOrderline())
				|| StringUtils.isEmpty(data17.getOrg()) || StringUtils.isEmpty(data17.getMaterialcode()) || StringUtils.isEmpty(data17.getQacode())
				|| StringUtils.isEmpty(data17.getLength()) || StringUtils.isEmpty(data17.getSalescode()) || StringUtils.isEmpty(data17.getSalesname())
				|| StringUtils.isEmpty(data17.getFactoryid())) {
			logger.info("工单号为:"+data17.getEntityno()+"的数据存在非法空值！参数如下："+"\n"+ "entityno:"+data17.getEntityno()+"\n"+
					"orderno:"+data17.getOrderno()+"\n"+ "orderline:"+data17.getOrderline()+"\n"+ "org:"+data17.getOrg()+"\n"+
					"materialcode:"+data17.getMaterialcode()+"\n"+ "qacode:"+data17.getQacode()+"\n"+ "length:"+data17.getLength()+"\n"+
					"salescode:"+data17.getSalescode()+"\n"+ "salesname:"+data17.getSalesname()+"\n"+ "factoryid:"+data17.getFactoryid()+"\n"+
					"drumname:"+data17.getDrumname()+"\n"+"isoutcoop:"+data17.getIsoutcoop()+"\n");
			resultMap = new HashMap<String, Object>(2) {{
				put("code", 1);
				put("msg", "输入参数存在非法空值");
			}};
			interfaceLogDAO.insertLog("FEWMS017", "标签信息初始化（1自产）", para, JSONObject.toJSONString(resultMap),data17.getQacode(), "");
			logger.info("#####	wms---->>>>>ebs	标签初始化FEWMS017：" + JSONObject.toJSONString(resultMap));
			return resultMap;
		}else if(StringUtils.isBlank(data17.getDrumname())){
			data17.setDrumname("1327100013");
		}

		String batchNo = "";

		try{
			while (ConRunningMap.containsItem(EbsInterfaceEnum.FEWMS017 + data17.qacode)){
				TimeUnit.MILLISECONDS.sleep(5000);
			}
			ConRunningMap.addItem(EbsInterfaceEnum.FEWMS017 + data17.qacode);

			batchNo = data17.getBatchno();
			String qacode = data17.getQacode();
			InstorageDetail instorageDetail;

			//如果批次号为空，则为新增
			if(StringUtils.isBlank(batchNo)){
				Long instorageId;

				//获取序列
				int seqRfid = fewmDAO.selectSeqRfid();
				String rfid = new DecimalFormat("000000000000").format(seqRfid);

				List<Instorage> lstInstorage = instorageDAO.selectList(new EntityWrapper<Instorage>()
						.eq("ORDERNO", data17.getOrderno())
						.eq("ORDERLINE", data17.getOrderline())
						.eq("ORG", data17.getOrg()));
				if(lstInstorage.size()==0) {
					Instorage instorage = new Instorage();
					//工单号
					instorage.setEntityNo(data17.getEntityno());
					//订单编号
					instorage.setOrderNo(data17.getOrderno());
					//数据创建时间
					instorage.setCreateTime(new Date());
					//订单行号
					instorage.setOrderline(data17.getOrderline());
					instorage.setOrg(data17.getOrg());
					instorageDAO.insert(instorage);
					instorageId = instorage.getId();
				}else {
					instorageId = lstInstorage.get(0).getId();
				}

				//根据质保号,存在就更新，不存在才新增
				boolean qacodeExist = instorageDetailDAO.selectCount(new EntityWrapper<InstorageDetail>().eq("QACODE", qacode))>0;
				if(qacodeExist){
					instorageDetail = instorageDetailDAO.selectByMap(new HashMap<String,Object>(1) {{
						put("QACODE",qacode);
					}}).get(0);
				} else {
					instorageDetail = new InstorageDetail();
					instorageDetail.setBatchNo(rfid);
					instorageDetail.setRfid(rfid);
				}
				//原报验单号
				String olsInspectno = instorageDetail.getInspectno();

				instorageDetail.setOrg(data17.getOrg());
				instorageDetail.setMaterialCode(data17.getMaterialcode());
				instorageDetail.setQaCode(qacode);
				instorageDetail.setSalesCode(data17.getSalescode());
				instorageDetail.setSalesName(data17.getSalesname());
				instorageDetail.setPId(instorageId);
				instorageDetail.setCreatetime(new Date());
				instorageDetail.setEntityNo(data17.getEntityno());
				instorageDetail.setFactoryid(data17.getFactoryid());
				instorageDetail.setSegmentno(data17.getSegmentno());
				//0自产；2外协安缆
				instorageDetail.setStoragetype("Y".equals(data17.getIsoutcoop()) ? 2L : 0L);
				instorageDetail.setColour(data17.getColour());
				instorageDetail.setWeight(data17.getWeight());
				//销售订单行号
				instorageDetail.setOrderline(data17.getOrderline());
				//销售订单号
				instorageDetail.setOrdernum(data17.getOrderno());
				//传入盘具编码
				instorageDetail.setDishnumber(data17.getDrumname());
				instorageDetail.setMeter(data17.getLength());
				instorageDetail.setUnit(data17.getUom());
				instorageDetail.setClientip(data17.getClientip());
				instorageDetail.setInspectno(data17.getInspectno());

				if(qacodeExist) {
					instorageDetailDAO.updateById(instorageDetail);
					//判断是否生成过了接口，如果生成了，修改接口中的报验单号
					List<InterfaceDo> lstInterfaceDo = interfaceDoDAO.selectList(new EntityWrapper<InterfaceDo>()
							.eq("QACODE", instorageDetail.getQaCode())
							.eq("INTERFACECODE", EbsInterfaceEnum.FEMES001));
					if (lstInterfaceDo.size()>0 && !olsInspectno.equals(data17.getInspectno())){
						InterfaceDo interfaceDo = lstInterfaceDo.get(0);
						interfaceDo.setParamsinfo(interfaceDo.getParamsinfo().replace(olsInspectno,data17.getInspectno()));
						interfaceDoDAO.updateById(interfaceDo);
					}
				} else {
					instorageDetailDAO.insert(instorageDetail);
				}

				resultMap = new HashMap<String, Object>(3) {{
					put("code", 0);
					put("batchNo", qacodeExist ? instorageDetail.getBatchNo() : rfid);
					put("msg", "成功");
				}};
			}else{
				//修改
				instorageDetail = instorageDAO.selectByBatch(batchNo);
				if(instorageDetail != null){
					String oldInspectno = instorageDetail.getInspectno();
					Instorage instorage = instorageDAO.selectById(instorageDetail.getPId());
					instorage.setOrg(data17.getOrg());
					instorage.setEntityNo(data17.getEntityno());
					instorage.setOrderNo(data17.getOrderno());
					instorage.setOrderline(data17.getOrderline());
					instorageDAO.updateById(instorage);

					instorageDetail.setOrg(data17.getOrg());
					instorageDetail.setFactoryid(data17.getFactoryid());
					instorageDetail.setMaterialCode(data17.getMaterialcode());
					instorageDetail.setQaCode(qacode);
					//销售订单号
					instorageDetail.setOrdernum(data17.getOrderno());
					//销售订单行号
					instorageDetail.setOrderline(data17.getOrderline());
					instorageDetail.setMeter(data17.getLength());
					instorageDetail.setUnit(data17.getUom());
					instorageDetail.setSegmentno(data17.getSegmentno());
					instorageDetail.setDishnumber(data17.getDrumname());
					instorageDetail.setSalesCode(data17.getSalescode());
					instorageDetail.setSalesName(data17.getSalesname());
					instorageDetail.setColour(data17.getColour());
					instorageDetail.setWeight(data17.getWeight());
					instorageDetail.setClientip(data17.getClientip());
					instorageDetail.setInspectno(data17.getInspectno());
					instorageDetailDAO.updateById(instorageDetail);

					//判断是否生成过了接口，如果生成了，修改接口中的报验单号
					List<InterfaceDo> lstInterfaceDo = interfaceDoDAO.selectList(new EntityWrapper<InterfaceDo>()
							.eq("QACODE", instorageDetail.getQaCode())
							.eq("INTERFACECODE", EbsInterfaceEnum.FEMES001));
					if (lstInterfaceDo.size()>0 && !oldInspectno.equals(data17.getInspectno())){
						InterfaceDo interfaceDo = lstInterfaceDo.get(0);
						interfaceDo.setParamsinfo(interfaceDo.getParamsinfo().replace(oldInspectno,data17.getInspectno()));
						interfaceDoDAO.updateById(interfaceDo);
					}

					resultMap = new HashMap<String, Object>(2) {{
						put("code", 0);
						put("msg", "成功");
					}};
				}else{
					resultMap = new HashMap<String, Object>(2) {{
						put("code", 1);
						put("msg", "该批次号不存在，请核对！");
					}};
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			resultMap.put("code", 1);
			resultMap.put("msg", e.getStackTrace());
		}

		ConRunningMap.removeItem(EbsInterfaceEnum.FEWMS017 + data17.getQacode());
		interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS017, StringUtils.isBlank(batchNo) ? "标签信息初始化（新增）" : "标签信息初始化（修改）", para,
				JSONObject.toJSONString(resultMap), data17.getQacode(), data17.getBatchno());
		logger.info("#####	wms---->>>>>mes	标签初始化FEWMS017：" + JSONObject.toJSONString(resultMap));
		return resultMap;
    }

    /**
     * FEWMS021 外协采购数据同步
     * @param para
     * @return Map<String,Object>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> FEWMS021(String para) {
		logger.info("#####	ebs---->>>>>wms	外协采购数据同步FEWMS021：" + para);
        FEWMS021_items data21 = null;
        Map<String,Object> resultMap = Maps.newHashMap();
        try {
            data21 = JaxbUtil.xmlToBean(para, FEWMS021_items.class);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        
        if(data21 != null && data21.getItem() != null) {
			InstorageDetail instorageDetail;
			Long instorageId;
			Instorage instorage;

	        for (FEWMS021_data fewms021Data : data21.getItem()) {
	        	try{
					while (ConRunningMap.containsItem(EbsInterfaceEnum.FEWMS021 + fewms021Data.getQacode())){
						TimeUnit.MILLISECONDS.sleep(5000);
					}
					//把接口编码+质保号放到内存中
					ConRunningMap.addItem(EbsInterfaceEnum.FEWMS021 + fewms021Data.getQacode());

					//如果传过来的盘具为空，那么给予默认盘具
					if(StringUtils.isBlank(fewms021Data.getDrummodel())) {
						fewms021Data.setDrumname("1327100013");
					}
					if(StringUtils.isEmpty(fewms021Data.getOrgid()) || StringUtils.isEmpty(fewms021Data.getQacode()) ||
							StringUtils.isEmpty(fewms021Data.getInspectionno()) || StringUtils.isEmpty(fewms021Data.getMaterialcode())) {
						resultMap = new HashMap<String, Object>(2) {{
							put("code", 1);
							put("msg", "质保号为:"+fewms021Data.getQacode()+"的数据存在非法空值！参数如下："+"\n"+ "qacode:"+fewms021Data.getQacode()+"\n"+
									"orgid:"+fewms021Data.getOrgid()+"\n"+ "inspectionno:"+fewms021Data.getInspectionno()+"\n"+ "materialcode:"+
									fewms021Data.getMaterialcode()+"\n"+ "length:"+fewms021Data.getLength()+"\n"+ "uom:"+fewms021Data.getUom());
						}};
					}else {
						List<Instorage> lstInstorage = instorageDAO.selectList(new EntityWrapper<Instorage>()
								.eq("ORDERNO", fewms021Data.getOrderno())
								.eq("ORDERLINE", fewms021Data.getOrderline())
								.eq("ORG", fewms021Data.getOrgid()));
						if(lstInstorage.size()==0) {
							instorage = new Instorage();
							//接收单号
							instorage.setEntityNo(fewms021Data.getEntityno());
							//订单编号
							instorage.setOrderNo(fewms021Data.getOrderno());
							//数据创建时间
							instorage.setCreateTime(new Date());
							//订单行号
							instorage.setOrderline(fewms021Data.getOrderline());
							instorage.setOrg(fewms021Data.getOrgid());
							instorageDAO.insert(instorage);
							instorageId = instorage.getId();
						}else {
							instorageId = lstInstorage.get(0).getId();
						}
						InstorageDetail iDetail = instorageDetailDAO.selectOne(new InstorageDetail() {{
							setQaCode(fewms021Data.getQacode());
						}});

						if(iDetail==null) {
							instorageDetail = new InstorageDetail();
							//新批次号、rfid
							String rfidBatchno = new DecimalFormat("000000000000").format(fewmDAO.selectSeqRfid());
							instorageDetail.setBatchNo(rfidBatchno);
							instorageDetail.setRfid(rfidBatchno);
						} else {
							instorageDetail = iDetail;
						}

						//旧报验单号
						String oldInspectno = instorageDetail.getInspectno();

						instorageDetail.setMaterialCode(fewms021Data.getMaterialcode());
						instorageDetail.setPId(instorageId);
						instorageDetail.setQaCode(fewms021Data.getQacode());
						instorageDetail.setSalesCode(fewms021Data.getSalescode());
						instorageDetail.setSalesName(fewms021Data.getSalesname());
						instorageDetail.setCreatetime(new Date());
						//外采
						instorageDetail.setStoragetype(2L);
						instorageDetail.setMeter(fewms021Data.getLength());
						instorageDetail.setUnit(fewms021Data.getUom());
						instorageDetail.setOrg(fewms021Data.getOrgid());
						instorageDetail.setFactoryid(fewms021Data.getFactoryid());
						//接受单号
						instorageDetail.setEntityNo(fewms021Data.getEntityno());
						instorageDetail.setOrdernum(fewms021Data.getOrderno());
						instorageDetail.setOrderline(fewms021Data.getOrderline());
						instorageDetail.setDishnumber(fewms021Data.getDrumname());
						instorageDetail.setInspectno(fewms021Data.getInspectionno());
						//护套颜色
						instorageDetail.setColour(fewms021Data.getColour());
						instorageDetail.setWeight(fewms021Data.getWeight());

						if(iDetail==null) {
							instorageDetailDAO.insert(instorageDetail);
						}else {
							instorageDetailDAO.updateById(instorageDetail);
							//判断是否生成过了接口，如果生成了，修改接口中的报验单号
							List<InterfaceDo> lstInterfaceDo = interfaceDoDAO.selectList(new EntityWrapper<InterfaceDo>()
									.eq("QACODE", instorageDetail.getQaCode())
									.eq("INTERFACECODE", EbsInterfaceEnum.FEWMS025));
							if (lstInterfaceDo.size()>0 && !oldInspectno.equals(fewms021Data.getInspectionno())){
								InterfaceDo interfaceDo = lstInterfaceDo.get(0);
								interfaceDo.setParamsinfo(interfaceDo.getParamsinfo().replace(oldInspectno,fewms021Data.getInspectionno()));
								interfaceDoDAO.updateById(interfaceDo);
							}
						}

						resultMap.put("code", 0);
						resultMap.put("msg", "成功");
					}
				}catch (Exception e){
	        		e.printStackTrace();
				}

				ConRunningMap.removeItem(EbsInterfaceEnum.FEWMS021 + fewms021Data.getQacode());
	        }
        }

		interfaceLogDAO.insertLog("FEWMS021", "WMS接口-外协采购数据同步", para, JSONObject.toJSONString(resultMap), "","");
		logger.info("#####	wms---->>>>>ebs	外协采购数据同步FEWMS021：" + JSONObject.toJSONString(resultMap));
        return resultMap;
    }

	/**
	 * FEWMS201 WMS接口-原材料采购订单/委外加工订单-数据同步
	 * @param  para
	 * @return Map<String,Object>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> FEWMS201(String para) {
//		logger.info("#####	ebs---->>>>>wms	采购订单数据同步FEWMS201：" + para);
		Map<String,Object> resultMap = new HashMap<>(2);
//		FEWMS201_data data_201 = null;
//		try {
//			data_201 = JaxbUtil.xmlToBean(para, FEWMS201_data.class);
//
//		} catch (JAXBException e) {
//			e.printStackTrace();
//		}
//
//		//手动new出来抛出的异常或手动return返回，不会回滚数据库事务，所以需要在解析数据保存前，先对数据进行空值判断
//		if(data_201!=null && data_201.getOrderLines()!=null) {
//			if(StringUtils.isEmpty(data_201.getPoCode())){
//				logger.info("采购订单编号存在非法空值,\n");
//			}
//
//		}else {
//			resultMap = new HashMap<String, Object>(2) {{
//				put("code", 1);
//				put("msg", "失败，采购订单同步数据为空!");
//			}};
//			interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS201, "WMS二期接口-采购订单数据同步", para, JSONObject.toJSONString(resultMap),"","");
//			logger.info("#####	ebs---->>>>>wms	采购订单数据同步FEWMS201：" + JSONObject.toJSONString(resultMap));
//			return resultMap;
//		}

//		String poCode = data_201.poCode;
//		PurchaseOrderEntity po = new PurchaseOrderEntity();
//		po.setPoCode(poCode);
//		int count = purchaseOrderDAO.selectCountByPoCode(poCode);
//		if(count>0){
//			//采购订单已存在，说明版本有更新，设置订单有效状态为“已过期”
//			List<PurchaseOrderEntity> poList = purchaseOrderDAO.SelectPurchaseOrders(po);
//			for(int i=0;i<poList.size();i++){
//				Long matepoId = poList.get(i).getPoHeaderId();
//				HashMap map1 = new HashMap<String,Object>();
//				map1.put("poHeaderId",matepoId);
//				map1.put("validState","2");
//				purchaseOrderDAO.update(map1);
//			}
//		}
//
//		//采购订单状态为“已取消”，说明EBS中该订单被取消了
//		if(data_201.state.equals(ORDER_STATE_CANCEL)){
//			//订单已取消
//			List<PurchaseOrderEntity> list = purchaseOrderDAO.SelectPurchaseOrders(po);
//			HashMap map3 = new HashMap<String,Object>();
//			Long matepoId = list.get(0).getPoHeaderId();
//			map3.put("poHeaderId",matepoId);
//			map3.put("state",data_201.state);
//			purchaseOrderDAO.update(map3);
//
//			resultMap.put("code", 0);
//			resultMap.put("poCode",poCode);
//			resultMap.put("msg", "成功");
//			interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS201, "WMS接口-采购订单数据同步", para, JSONObject.toJSONString(resultMap),"", "");
//			logger.info("#####	ebs---->>>>>wms	采购订单数据同步FEWMS201：" + JSONObject.toJSONString(resultMap));
//			return resultMap;
//		}
//
//
//
//		DateTimeFormatter df = DateTimeFormatter.ofPattern(Constant.DATE_TIME_PATTERN);
//		LocalDateTime orderTime = LocalDateTime.parse(data_201.orderTime, df);
//
////id,po_code,order_time,supplier_code,supplier_name,purchase_organ,purchase_dept,
////        purchase_user,remark,state,create_user,create_time,place,contact,currency,po_type,revision,valid_state
//		PurchaseOrderEntity purchaseOrder = new PurchaseOrderEntity();
//		purchaseOrder.setContact(data_201.contact);
//		purchaseOrder.setCreateTime(LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai"))));
//		purchaseOrder.setCreateUser(data_201.createUser);
//		purchaseOrder.setCurrency(data_201.currency);
//		purchaseOrder.setOrderTime(orderTime);
//		purchaseOrder.setPlace(data_201.place);
//		purchaseOrder.setPoCode(poCode);
//		purchaseOrder.setPurchaseOrgan(data_201.purchaseOrgan);
//		purchaseOrder.setPurchaseUser(data_201.purchaseUser);
//		purchaseOrder.setRemark(data_201.remark);
//		purchaseOrder.setState(data_201.state);
//		purchaseOrder.setSupplierCode(data_201.supplierCode);
//		purchaseOrder.setSupplierName(data_201.supplierName);
//		purchaseOrder.setRevision(data_201.revision);
//		purchaseOrder.setPurchaseOrganId(data_201.purchaseOrganId);
//		purchaseOrder.setPurchaseUserId(data_201.purchaseUserId);
//		purchaseOrder.setPurchaseDeptId(data_201.shipToLocationId);
//		purchaseOrder.setPurchaseDept(data_201.locationCode);
//
//		Long mainId = purchaseOrderDAO.getSequence();
//		purchaseOrder.setPoHeaderId(mainId);
//		//默认值1是采购订单
//		String poType = new String("1");
//
//		if(data_201.getOrderLines() != null && data_201.getOrderLines().size()>0){
//			List<FEWMS201_orderline> line =  data_201.getOrderLines().get(0).getOrderLine();
//			for(int i=0;i<line.size();i++){
//
//				PurchaseOrderLineEntity pol = new PurchaseOrderLineEntity();
//				Long poLineId = purchaseOrderLineDAO.getSequence();
//				pol.setPoHeaderId(String.valueOf(mainId));
//				pol.setRatio(line.get(i).ratio);
//				pol.setQuantity(new BigDecimal(line.get(i).quantity));
//				pol.setPrimaryUnit(line.get(i).primaryUnit);
//				pol.setWxitemCode(line.get(i).wxitemCode);
//				pol.setWxitemName(line.get(i).wxitemDesc);
//				pol.setMaterialName(line.get(i).materialName);
//				pol.setMaterialCode(line.get(i).materialCode);
//				pol.setPoLineNum(line.get(i).poLineNum);
//				pol.setExpired("0");//代表行订单有效
//				pol.setPrice(line.get(i).price);
//				pol.setPoLineId(String.valueOf(poLineId));
//
//				//purchaseOrderLineDAO.insertPurchaseOrderLine(pol);
//				int iResult = purchaseOrderLineDAO.insert(pol);
//				if(StringUtils.isNotEmpty(line.get(i).getWxitemCode())){
//					//2代表委外加工订单
//					poType = "2";
//				}
//			}
//		}
//		purchaseOrder.setPoType(poType);
//		purchaseOrder.setValidState("1");
//		purchaseOrderDAO.insertPurchaseOrder(purchaseOrder);
//		//int headResult = purchaseOrderDAO.insert(purchaseOrder);
//
//		resultMap.put("code", 0);
//		resultMap.put("msg", "成功");
//		resultMap.put("poCode",poCode);
//
//		interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS201, "WMS接口-采购订单数据同步", para, JSONObject.toJSONString(resultMap),"", "");
//		logger.info("#####	ebs---->>>>>wms	采购订单数据同步FEWMS201：" + JSONObject.toJSONString(resultMap));
		return resultMap;
	}

	/**
	 * FEWMS202 WMS接口-送货单-数据同步
	 * @param  para
	 * @return Map<String,Object>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> FEWMS202(String para) {
		logger.info("#####	ebs---->>>>>wms	送货单数据同步FEWMS202：" + para);
		Map<String,Object> resultMap = new HashMap<>(2);
		FEWMS202_data data_202 = null;
		try {
			data_202 = JaxbUtil.xmlToBean(para, FEWMS202_data.class);

		} catch (JAXBException e) {
			e.printStackTrace();
		}

		//手动new出来抛出的异常或手动return返回，不会回滚数据库事务，所以需要在解析数据保存前，先对数据进行空值判断
		if(data_202!=null && data_202.getDeliveryCode()!=null) {
			if(StringUtils.isEmpty(data_202.getDeliveryCode())){
				logger.info("送货单编号存在非法空值,\n");
			}

		}else {
			resultMap = new HashMap<String, Object>(2) {{
				put("code", 1);
				put("msg", "失败，送货单同步数据为空!");
			}};
			interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS202, "WMS二期接口-送货单数据同步", para, JSONObject.toJSONString(resultMap),"","");
			logger.info("#####	ebs---->>>>>wms	送货单数据同步FEWMS202：" + JSONObject.toJSONString(resultMap));
			return resultMap;
		}

//		String deliveryCode = data_202.deliveryCode;
//		int count = matepoDAO.selectCountByPoCode(deliveryCode);
//		if(count>0){
//			//采购订单已存在，说明版本有更新，设置订单有效状态为“已过期”
//			List<Matepo> matepoList = matepoDAO.getMatepoListByPoCode(deliveryCode);
//			for(int i=0;i<matepoList.size();i++){
//				Long matepoId = matepoList.get(i).getId();
//				HashMap map1 = new HashMap<String,Object>();
//				map1.put("id",matepoId);
//				map1.put("validState","2");
//				matepoDAO.update(map1);
//			}
//		}



		resultMap.put("code", 0);
		resultMap.put("msg", "成功");
//		resultMap.put("deliveryCode",deliveryCode);

		interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS202, "WMS接口-送货单数据同步", para, JSONObject.toJSONString(resultMap),"", "");
		logger.info("#####	ebs---->>>>>wms	送货单数据同步FEWMS202：" + JSONObject.toJSONString(resultMap));

		return resultMap;

	}


	/**
	 * 紧急物料信息查询
	 * @param para
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String FEWMS203(String para){
		logger.info("#####	OA---->>>>>wms	查询接收单信息 FEWMS203：" + para);
		Map<String,Object> resultMap;
		FEWMS203_data data_203 = null;
		try {
			data_203 = JaxbUtil.xmlToBean(para, FEWMS203_data.class);
		} catch (JAXBException e) {
			e.printStackTrace();
		}

		//手动new出来抛出的异常或手动return返回，不会回滚数据库事务，所以需要在解析数据保存前，先对数据进行空值判断
		if(data_203!=null && data_203.getDeliveryNo()!=null) {
			if(StringUtils.isEmpty(data_203.getDeliveryNo())){
				logger.info("接收单号存在非法空值,\n");
			}
		}else {
			resultMap = new HashMap<String, Object>(2) {{
				put("code", 1);
				put("msg", "失败，接收单号查询数据为空!");
			}};
			interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS203, "WMS二期接口-接收单信息查询", para, JSONObject.toJSONString(resultMap),"","");
			logger.info("#####	OA---->>>>>wms	接收单信息查询FEWMS203：" + JSONObject.toJSONString(resultMap));
			return XmlToolsUtil.getResponseXml(resultMap);
		}

		String deliveryNo = data_203.deliveryNo;
		String deliveryLineNo = data_203.deliveryLineNo;
		//根据接收单号查询接收单数据(筛选掉已经发起过OA审批的数据)，从数据中并取出采购订单号和行号用于紧急物料视图数据的查询
		Map<String,Object> map = new HashMap<>();
		map.put("deliveryLineNo",deliveryLineNo);
		map.put("deliveryNo",deliveryNo);
		DeliveryEntity deliveryEntity = deliveryDao.selectDeliveryBydeliveryLineNo(map);
		if(deliveryEntity==null){
			resultMap = new HashMap<String, Object>(2) {{
				put("code", 1);
				put("msg", "失败，当前接收单号无数据或正在审批中!");
			}};
			return XmlToolsUtil.getResponseXml(resultMap);
		}

		String lotsNum = deliveryEntity.getLotsNum();

		String poNumber = deliveryEntity.getPoCode();
		String lineNum = deliveryEntity.getPoLineNum();
		BigDecimal receiveQuantity = deliveryEntity.getReceiveQuantity();

		Map<String,Object> paraMap = new HashMap<>();
		paraMap.put("poNumber",poNumber);
		paraMap.put("lineNum",lineNum);

		FEWMS203_data fewms203_data = qualityInfoDAO.selectEmergencyByPoNumberAndLineNumber(paraMap);
		String facName = "";
		if(StringUtils.isNotEmpty(fewms203_data.getFacName())){
			facName = fewms203_data.getFacName();
		}
		String orderNumber = "";
		String orderLineNumber = "";
		String salesrepName = "";
		if(StringUtils.isNotEmpty(fewms203_data.getOrderNumber())){
			orderNumber = fewms203_data.getOrderNumber();
		}
		if(StringUtils.isNotEmpty(fewms203_data.getOrderLineNumber())){
			orderLineNumber = fewms203_data.getOrderLineNumber();
		}
		if(StringUtils.isNotEmpty(fewms203_data.getSalesrepName())){
			salesrepName = fewms203_data.getSalesrepName();
		}

		fewms203_data.setFacName(facName);
		fewms203_data.setOrderNumber(orderNumber);
		fewms203_data.setOrderLineNumber(orderLineNumber);
		fewms203_data.setSalesrepName(salesrepName);
		fewms203_data.setQuantity(receiveQuantity);
		fewms203_data.setDeliveryNo(deliveryNo);
		fewms203_data.setDeliveryLineNo(deliveryLineNo);
		fewms203_data.setLotsNum(lotsNum);


		return JavaBeanToXml.converTomXml(fewms203_data);

	}

	/**
	 * OA紧急物料审批结果接收-服务端
	 * @param para
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Map<String,Object> FEWMS204(String para){
		logger.info("#####	OA---->>>>>wms	OA紧急物料审批结果返回 FEWMS204：" + para);
		Map<String,Object> resultMap;
		FEWMS204_data data_204 = null;
		try {
			data_204 = JaxbUtil.xmlToBean(para, FEWMS204_data.class);
		} catch (JAXBException e) {
			e.printStackTrace();
		}

		//手动new出来抛出的异常或手动return返回，不会回滚数据库事务，所以需要在解析数据保存前，先对数据进行空值判断
		if(data_204!=null && data_204.getQcLines().size()>0) {
			for(int i=0,j=data_204.getQcLines().get(0).getQcLine().size();i<j;i++){
				if(StringUtils.isEmpty(String.valueOf(data_204.getQcLines().get(0).getQcLine().get(i).deliveryNo))
						|| StringUtils.isEmpty(String.valueOf(data_204.getQcLines().get(0).getQcLine().get(i).deliveryLineNo))){
					logger.info("接收单号或行号存在非法空值,\n");
				}
			}
		}else {
			resultMap = new HashMap<String, Object>(2) {{
				put("code", 1);
				put("msg", "失败，OA紧急物料审批结果返回为空!");
			}};
			interfaceLogDAO.insertLog(EbsInterfaceEnum.FEWMS204, "WMS二期接口-OA紧急物料审批结果返回", para, JSONObject.toJSONString(resultMap),"","");
			logger.info("#####	OA---->>>>>wms	接收单信息查询FEWMS204：" + JSONObject.toJSONString(resultMap));
			return resultMap;
		}


		List<QualityInfoEntity> lists = new ArrayList<>();
		for(int i=0,j=data_204.getQcLines().get(0).getQcLine().size();i<j;i++){
			List<FEWMS204_oa_qcline> list = data_204.qcLines.get(0).getQcLine();
			String deliveryNo = list.get(i).getDeliveryNo();
			String deliveryLineNo = list.get(i).getDeliveryLineNo();
			String isPass = list.get(i).getIsPass();//保存到质检信息表pass_oa字段
			String oaState = list.get(i).getOaState();//保存到质检信息表oa_pass字段
			//TODO 下面会空值报错

			Map<String,Object> map = new HashMap<>();
			map.put("deliveryNo",deliveryNo);
			map.put("deliveryLineNo",deliveryLineNo);

			List<QualityInfoEntity> qualityInfoEntityList = qualityInfoService.getQualityInfoList(map);
			QualityInfoEntity qualityInfoEntity = new QualityInfoEntity();
			qualityInfoEntity.setPassOa(isPass);
			qualityInfoEntity.setOaState(oaState);
			qualityInfoEntity.setId(qualityInfoEntityList.get(0).getId());

			boolean dd = false;
			//更新接收表质检状态并入库，后期是否改成批处理? TODO
			if(isPass.equals("1")){//审批结果为"通过"
				dd = qualityInfoService.updateQcStateForDelivery(deliveryNo,deliveryLineNo);
			}
			//质检表数据，需要更新质检结果
			lists.add(qualityInfoEntity);

		}
		boolean b = qualityInfoService.updateBatchById(lists);

		resultMap = new HashMap<String,Object>();
		if(b){
			resultMap.put("code", 0);
			resultMap.put("msg", "成功");
		}else{
			resultMap.put("code", 1);
			resultMap.put("msg", "保存质检信息失败!");
		}

		return resultMap;


	}

}
